<?php
/**
 * 获取微信的openid
 * Created by PhpStorm.
 * CeshiUser: leesin
 * Date: 2018/4/26
 * Time: 16:05
 */
namespace app\index\model;
use think\Session;
class OpenIdModel{
    //定义成员属性
    const GET_CODE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize';
    const GET_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    const REFRESH_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
    const TEST_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/auth';
    const GET_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo';

    public $urlUtil;
    public $appid = 'wx292e1491eca7a249';
    public $redirect_uri = 'http://pay.importndsf.com/import_nbsm/nbsm_shopping/public/index.php/index/GetOpenId/index';
    public $secret = '7dae8aa84a022ac8e160448f01523345';
    public $scope = 'snsapi_base';

    //构造函数(初始化Url类)
    public function __construct(){
        $this->urlUtil = new UrlUtil();
    }

    //获取code
    public function getOpenId(){
        $state = MD5(uniqid());
        Session::set('state',$state);
        $paramArr = array(
            'appid'         =>  $this->appid,
            'redirect_uri'  =>  urlencode($this->redirect_uri),
            'response_type' =>  'code',
            'scope'         =>  $this->scope,
            'state'         =>  $state,
        );

        return $this->urlUtil->combineUrl(self::GET_CODE_URL, $paramArr).'#wechat_redirect';
    }

    //通过code获取access_token
    public function getAccessToken(){
        //此处应该根据state判断一下是否跨域攻击
        dump($_GET);die;
        $code = $_GET['code'];
        $paramArr = array(
            'appid'         =>      $this->appid,
            'secret'        =>      $this->secret,
            'code'          =>      $code,
            'grant_type'    =>      'authorization_code'
        );
        $response = $this->urlUtil->get(self::GET_ACCESS_TOKEN_URL, $paramArr);
        $arr = json_decode($response,true);
        return $arr['refresh_token'];
    }

    //刷新或续期access_token使用
    public function refreshAccessToken($refresh_token){
        $paramArr = array(
            'appid'         =>      $this->appid,
            'grant_type'    =>      'refresh_token',
            'refresh_token' =>      $refresh_token
        );
        $response = $this->urlUtil->get(self::REFRESH_ACCESS_TOKEN_URL, $paramArr);
        $arr = json_decode($response,true);
        return $arr['openid'];
    }

}